package com.content.scaffold.common.utils;

import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.lang3.StringUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;

/**
 * @author xiaojl
 */
public class ThumbUtils {


    public static byte [] thumbnails(byte[] bytes, int fixWidth) throws IOException {
        ByteArrayOutputStream  outputStream = new ByteArrayOutputStream();
        BufferedImage bim = ImageIO.read(new ByteArrayInputStream(bytes));
        int srcWidth = bim.getWidth();
        if (srcWidth > fixWidth) {
            int srcHeight = bim.getHeight();
            int destWidth = new BigDecimal(srcWidth).compareTo(new BigDecimal(fixWidth)) < 0 ? srcWidth : fixWidth;
            int destHeight = new BigDecimal((srcHeight * destWidth) / srcWidth).intValue();
            Thumbnails.of(bim).size(destWidth, destHeight).outputFormat("jpg").toOutputStream(outputStream);
        }
        return outputStream.toByteArray();
    }

    public static byte [] thumbnails(byte[] bytes) throws IOException{
        return thumbnails(bytes,300);
    }

    public static File thumbnails(File sourceFile,int with,int height,String outDir) throws IOException {

        String fileName =
                StringUtils.join(System.getProperty("java.io.tmpdir")+File.separator,outDir+File.separator
                        ,sourceFile.getName().substring(0,sourceFile.getName().lastIndexOf(".")), "_thumb.jpg");
        File thumbFile = new File(fileName);
        Thumbnails.of(sourceFile).size(with, height).toFile(thumbFile);
        return thumbFile;
    }

    public static byte[] thumbnails(InputStream inputStream,int with,int height) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        Thumbnails.of(inputStream).size(with, height).outputFormat("jpg").toOutputStream(outputStream);
        return outputStream.toByteArray();
    }

    /**
     *  pdf 第一页的缩略图
     * @param source
     * @return
     */
    public static File pdfThumbnails(File source,String outDir){
        String outPath =
                StringUtils.join(System.getProperty("java.io.tmpdir")+File.separator,outDir+File.separator
                        ,source.getName().substring(0,source.getName().lastIndexOf(".")), "_thumb.jpg");
        try {
           File file  = PdfUtils.takeFirstPage(source,outPath,300);
           return ThumbUtils.thumbnails(file,300,300,outDir);
        } catch (IOException e) {
            e.printStackTrace();
            return  null;
        }
    }

    /**
     * pdf 第一页的缩略图
     * @param source
     * @return
     */
    public static byte[] pdfThumbnails(byte[] source){

        try {
            byte[] file  = PdfUtils.takeFirstPage(source,300);
            return ThumbUtils.thumbnails(file,300);
        } catch (IOException e) {
            e.printStackTrace();
            return  new byte[0];
        }
    }


}
